package com.da.javatest.niuke.jianzhi;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenlida
 * @date 2020/10/22 10:26
 * https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?
 * tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1
 */
public class C28Solution {
    public int MoreThanHalfNum_Solution(int[] array) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : array) {
            map.merge(i, 1, (a, b) -> a + b);
        }
        int half = array.length / 2;
        for (Integer key : map.keySet()) {
            if (map.get(key) > half) {
                return key;
            }
        }
        return 0;
    }

    public int MoreThanHalfNum_Solution2(int[] array) {
        Arrays.sort(array);
        int count = 0;
        int half = array.length / 2;
        for (int data : array) {
            if (data == array[half]) {
                count++;
            }
        }
        if (count > half) {
            return array[half];
        } else {
            return 0;
        }

    }
}
